from midi.midi_event import MidiEvent
from midi.serializable import Serializable

class Track(Serializable):
    MTRK_ID_CODE = "4d54726b" # MTrk 识别码

    __events: list[MidiEvent] # 事件列表

    def __init__(self) -> None:
        self.__events = list()

    def getEvents(self) -> list[MidiEvent]:
        return self.__events

    def appendEvent(self, event: MidiEvent) -> None:
        self.__events.append(event)

    def sortEvents(self) -> None:
        self.__events = sorted(self.__events, key=MidiEvent.getTick)
    
    def hex(self) -> str:
        self.sortEvents()
        s_data = ""
        datum_time = 0
        for event in self.__events:
            s_data += event.hex(datum_time)
            datum_time = event.getTick()
        s_data_length = hex(len(s_data)//2)[2:] # 音轨数据总字节数
        s_data_length = "0"*(8-len(s_data_length))+s_data_length
        return Track.MTRK_ID_CODE+s_data_length+s_data